import React, {useEffect, useRef, useState} from 'react'
import {Avatar, Card, Col, List, Row,Drawer} from "antd";
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import axios from "axios";
import * as Echarts from "echarts";
import _ from "loadsh"
const { Meta } = Card;

export default function Home() {
    const [viewList, setviewList] = useState([])
    const [starList, setstarList] = useState([])
    const [allList,setAllList]=useState([])
    const [visible,setVisible] = useState(false)
    const [pieChart,setPieChart] = useState(null)
    const barRef =useRef()
    const pieRef = useRef()
    useEffect(()=>{
        axios.get("/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6").then(res=>{
            setviewList(res.data)
        })
    },[])

    useEffect(()=>{
        axios.get("/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6").then(res=>{
            setstarList(res.data)
        })

    },[])

    useEffect(()=>{
        axios.get("/news?publishState=2&_expand=category").then(res=>{
            let list = _.groupBy(res.data,item=>item.category.title);//使用loadsh将数据分组
            setAllList(res.data)
            renderBar(list)
        })
        return ()=>{//组件销毁时，撤销监听器。
            window.onresize=null
        }
    },[])
    const renderBar =(list)=>{
        // 基于准备好的dom，初始化echarts实例
        let myChart = Echarts.init(barRef.current);
        // 指定图表的配置项和数据
        let option = {
            title: {
                text: "新闻分类图示"
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(list)//分组对象的所有key值（用一个数组）
            },
            yAxis: {
                minInterval: 1      //最小间隔
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(list).map(item=>item.length)
                    //分组对象的所有value值 [Array(2), Array(2), Array(2), Array(1), Array(1)]
                    //数量就是每个数组的长度
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.onresize=()=>{//监听器，每次窗口大小改变，触发
            myChart.resize();
        }
    }

    const renderPie = () => {
        let currentList = allList.filter(item=>item.author===username);
        let list = _.groupBy(currentList,item=>item.category.title);
        let dataList = []
        for(let key in list) {
            dataList.push({
                "value":list[key].length,
                "name":key,
            })
        }
        let myChart;
        if(!pieChart){
            myChart = Echarts.init(pieRef.current);
            setPieChart(myChart);
        }else{
            myChart=pieChart
        }

        let option = {
            title: {
                text: `${username}发布的新闻`,
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: 'Access From',
                    type: 'pie',
                    radius: '50%',
                    data: dataList,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        myChart.setOption(option);
    }
    const {username,region,role:{roleName}} = JSON.parse(localStorage.getItem("token"))
    const showDrawer = () => {
      //setVisible(true);
      /*
      * 状态是异步更新的，
      * */
        setTimeout(()=>{
            setVisible(true);
            renderPie();
        },0)
    }
    const onClose=()=>{
        setVisible(false);
    }

    return (
        <div className="site-card-wrapper">
            <Row gutter={16}>
                <Col span={8}>
                    <Card title="用户最常浏览" bordered={true}>
                        <List
                            size="small"
                            dataSource={viewList}
                            renderItem={item => <List.Item>
                                <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                            </List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card title="用户点赞最多" bordered={true}>
                        <List
                            size="small"
                            dataSource={starList}
                            renderItem={item => <List.Item>
                                <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                            </List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card
                        cover={
                            <img
                                alt="example"
                                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                            />
                        }
                        actions={[
                            <SettingOutlined key="setting" onClick={showDrawer} />,
                            <EditOutlined key="edit" />,
                            <EllipsisOutlined key="ellipsis" />,
                        ]}
                    >
                        <Meta
                            avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
                            title={username}
                            description={<div>
                                <b>{region?region:"全球"}</b>
                                <span style={{
                                    paddingLeft:"30px"
                                }}>{roleName}</span>
                            </div>}
                        />
                    </Card>
                </Col>
            </Row>
            <div ref={barRef} style={{height:"500px",marginTop:"40px"}}>
            </div>
            <Drawer width={"500px"} title="个人新闻分类" placement="right" closable={true} onClose={onClose} visible={visible}>
                <div ref={pieRef} style={{width:"400px",height:"100%"}}>

                </div>
            </Drawer>
        </div>
    )
}
